<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/8 13:35
*/
declare(strict_types=1);
namespace app\store\service\agent;

use app\common\model\agent\BindLog;
use app\common\service\BaseService;
use app\store\model\agent\Channel;
use app\store\model\agent\Rel;
use app\store\model\User;
use think\facade\Db;
use think\facade\Log;

class Bind extends BaseService
{
    /**绑定
     * @param $params
     * @return bool
     */
    public function getDone($params):bool
    {
        //先查看是否有用户存在
        $player_user = User::where(['user_id' => $params['player_user_id'],'is_delete' => 0])->find();
        if(!$player_user){
            throwError('玩家用户未注册');
        }
        $promoter_user = User::where(['user_id' => $params['promoter_user_id'],'is_delete' => 0])->find();
        if(!$promoter_user){
            throwError('推广员用户未注册');
        }

        $channel_user = Channel::where(['user_id' => $params['promoter_user_id'],'is_del' => 0])->find();
        $promoter_user = \app\store\model\agent\Promoter::where(['user_id' => $params['promoter_user_id'],'is_del' => 0])->find();
        if(!$channel_user && !$promoter_user){
            throwError('推广员不存在');
        }

        $channel_user = Channel::where(['user_id' => $params['player_user_id'],'is_del' => 0])->find();
        if($channel_user && ($params['player_user_id'] != $params['promoter_user_id'])){
            throwError('玩家属于渠道用户只能绑定自己，不能绑定其他用户');
        }

        if(!$channel_user && $params['player_user_id'] == $params['promoter_user_id']){
            throwError('自己不能绑定自己(只有渠道用户可以自己绑定自己)');
        }

        $bind_rel = Rel::where(['user_id' => $params['player_user_id'],'is_del' => 0])->find();
        if($bind_rel){
            throwError('该玩家已被绑定，请先解绑');
        }
        Db::startTrans();
        try {
            $rel = Rel::create([
                'user_id' => $params['player_user_id'],
                'promoter_user_id' => $params['promoter_user_id']
            ]);
            if(!$rel->id){
                return false;
            }
            //同时增加绑定日志
            $bind = BindLog::create([
                'promoter_user_id' => $params['promoter_user_id'],
                'player_user_id' => $params['player_user_id'],
                'type' => 1
            ]);
            if(!$bind->id){
                return false;
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            throwError($e->getMessage());
            return false;
        }
    }

    /**解绑
     * @param $params
     * @return bool
     */
    public function cancel($params):bool
    {
        $player_user = User::where('user_id',$params['player_user_id'])->find();
        if(!$player_user){
            throwError('玩家用户不存在');
        }
        //todo 玩家ID是否有绑定
        $bind_rel = Rel::where(['user_id' => $params['player_user_id'],'is_del' => 0])->find();
        if(!$bind_rel) throwError('绑定关系不存在');
        Db::startTrans();
        try {
            $bind_rel->is_del = 1;
            $bind_rel->save();
            User::update(['refer_id' => 0],['user_id' => $params['player_user_id']]);
            //同时增加解绑日志
            $bind = BindLog::create([
                'promoter_user_id' => $bind_rel->promoter_user_id,
                'player_user_id' => $params['player_user_id'],
                'type' => 2
            ]);
            if(!$bind->id){
                return false;
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            throwError($e->getMessage());
            return false;
        }

    }


    /**绑定日志列表
     * @param $params
     * @return array
     */
    public function getBindLogs($params):array
    {
        $condition = [];
        //1绑定 2解绑
        if(!empty($params['type']) || (isset($params['type']) && $params['type'] != '')){
            $condition[] = ['fw_agent_bind_log.type','=',$params['type']];
        }

        if(!empty($params['player_user_id'])){
            $condition[] = ['fw_agent_bind_log.player_user_id','=',$params['player_user_id']];
        }
        if(!empty($params['promoter_user_id'])){
            $condition[] = ['fw_agent_bind_log.promoter_user_id','=',$params['promoter_user_id']];
        }

        if(!empty($params['player_nick_name'])){
            $condition[] = ['u.nick_name','like',"%{$params['player_nick_name']}%"];;
        }

        $promoter_user_where = [];
        if(!empty($params['promoter_nick_name'])){
            $promoter_user_where[] = ['nick_name','like',"%{$params['promoter_nick_name']}%"];;
        }

        return BindLog::with(['promoterUser' => function($query){
            $query->field('user_id,nick_name,mobile');
        }])
            ->join('fw_user u','u.user_id = fw_agent_bind_log.player_user_id','LEFT')
            ->haswhere('promoterUser',$promoter_user_where)
            ->where($condition)
            ->field('fw_agent_bind_log.*,u.nick_name as player_nick_name,u.mobile')
            ->paginate($params['limit'] ?? 15)
            ->each(function (&$item){
                $item['playerUser'] = [
                    'user_id' => $item['player_user_id'],
                    'nick_name' => $item['player_nick_name'],
                    'mobile' => $item['mobile'],
                ];
                unset($item['player_nick_name']);
            })
            ->toArray();

    }


}